package src 
{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.ui.Keyboard;
	import src.actors.Actor;
	import src.actors.Player;
	import src.auxiliary.KeyboardHandler;
	import src.levels.BaseLevel;
	
	/**
	 * ...
	 * @author Morozov
	 */
	public class Engine extends MovieClip
	{
		public var level :Array;
		private var physObjects:Array;
		private var keyHandler:KeyboardHandler;
		private var objectContainer:MovieClip;
		public var currentLevel:BaseLevel;
		
		public var player:Player;
		
		public function Engine()
		{			
			this.objectContainer = new MovieClip();
			this.addChild(objectContainer);
			
			currentLevel = new BaseLevel();
			this.addChild(currentLevel);
			
			level = currentLevel.levelStructure;
			
			keyHandler = new KeyboardHandler();
			this.addChild(keyHandler);
			
			physObjects = new Array();
			
			player = new Player();
			player.px = 50;
			player.py = 40;
			this.objectContainer.addChild(player);
			this.physObjects.push(player);
			
			this.addEventListener(Event.ENTER_FRAME, update);
		}
		
		private function update(e:Event):void 
		{
			for (var i:int = 0; i < physObjects.length; i++)
			{
				if (physObjects[i] is Actor)
				{
					var cAct:Actor = physObjects[i];
					//cAct.updatePosition();
					cAct.velocity.y += 0.5;
					cAct.px += cAct.velocity.x;
					cAct.py += cAct.velocity.y;
					
					
					 
					cAct.x = cAct.px;
					cAct.y = cAct.py;
				}
			}
		}
		
		public function addActor(actor:Actor, coordinates:Point):Actor
		{
			actor.px = coordinates.x;
			actor.py = coordinates.y;
			
			actor = new Actor();
			
			this.objectContainer.addChild(actor);
			
			physObjects.push(actor);
			
			return actor;
		}
		
		public function getActorEdges(actor:Actor)
		{
			actor.left = Math.floor((actor.px - Math.floor(actor.width / 2)) / currentLevel.tileSize);
			actor.pleft = Math.floor((actor.px - Math.floor(actor.width/2) + Math.abs (actor.velocity.x)+1) / currentLevel.tileSize);
			actor.right = Math.floor((actor.px + Math.floor(actor.width/2)) / currentLevel.tileSize);
			actor.pright = Math.floor((actor.px + Math.floor(actor.width / 2) - Math.abs(actor.velocity.x)-1) / currentLevel.tileSize);
			actor.top = Math.floor((actor.py - Math.floor(actor.height / 2)) / currentLevel.tileSize);
			actor.bottom = Math.floor((actor.py + Math.floor(actor.height / 2)) / currentLevel.tileSize);
			trace(actor.bottom);
			actor.cnt = Math.floor((actor.py + Math.floor(actor.height/2)-Math.abs(actor.velocity.y) - 1) / currentLevel.tileSize);	
		}

		
	}

}